package com.itany.corejava.code12_线程;

/**
 * @author MissChen
 * @version 1.0
 * @date 2023 年11月29日 14:41
 */
public class Test10_同步方法 {
    public static void main(String[] args) {


        Ticket3 t1=new Ticket3();
        Ticket3 t2=new Ticket3();
        t1.setName("t1");
        t1.setPriority(5);
        t2.setName("t2");
        t1.start();
        t2.start();

        // TicketRunnaleThree t=new TicketRunnaleThree();
        // Thread t1=new Thread(t);
        // Thread t2=new Thread(t);
        // t1.start();
        // t2.start();

    }
}

class Ticket3 extends Thread{
    private static  int num=100;
    @Override
    public void run() {
        while(true){
            if(method2()){
                break;
            }
        }
    }
    //同步方法的锁对象没法手动指定
    //普通方法，锁对象指的是this
    //如果是静态方法,锁对象是所在类的字节码文件对象
    public synchronized boolean method(){
        if(num==0){
            return true;
        }else{
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"正在售票,当前第"+(num--));
        }
        return false;
    }


    //锁对象是所在类的字节码文件对象
    public static synchronized boolean method2(){
        if(num==0){
            return true;
        }else{
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"正在售票,当前第"+(num--));
        }
        return false;
    }
}




class TicketRunnaleThree implements Runnable{
    private int num=100;

    @Override
    public void run() {
        while(true){
            if(method()){
                break;
            }
        }
    }

    //同步方法的锁对象没法手动指定
    //普通方法，锁对象指的是this
    public synchronized boolean method(){
        if(num==0){
           return true;
        }else{
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"正在售票,当前第"+(num--));
        }
        return false;
    }

}